<template>
  <div id="processForm" v-loading="loading">
    <bm-form-realize
      ref="realize"
      v-if="processForm"
      :config="formConfig"
      @submit="formSubmit"
      v-model="formData"
      :axios="ajax"
      :getDic="getDic"
      :headers="token"
      :finishedData="finishedData"
    ></bm-form-realize>
  </div>
</template>

<script>
import request from "@/router/axios";
import { getBusinessDictTypes } from "@/api/process/process";

export default {
  data() {
    return {
      processForm: false,
      ajax: request,
      getDic: getBusinessDictTypes,
      formData: { historyNode: [] },
      loading: true,
      ajaxOption: {},
      formConfig: {},
      query: {},
      totalData: {},
      finishedData: {}
    };
  },
  watch: {},
  computed: {
    token() {
      return {
        "Blade-Auth": "bearer " + document.cookie.split(";")[0].split("=")[1]
      };
    }
  },
  created() {
    this.query = this.$route.query;
    if (this.query) {
      this.handlerGetConfig();
    } else {
      this.$message.warning("请传入流程信息！");
    }
  },
  methods: {
    handlerGetConfig() {
      //获取表单配置
      request
        .get(
          `/rem-registrationmgrweb/otc-flow/workflowform/detail?appId=${this.query.id}&nodeId=${this.query.nodeId}`
        )
        .then(res => {
          if (res) {
            this.formConfig = JSON.parse(decodeURI(res.data.data.formData));
            this.processForm = true;
            if (this.query.bizId) {
              this.handlerGetBizData(this.query.bizId);
            } else {
              this.loading = false;
            }
          }
        })
        .catch(() => {
          this.$message.error("获取表单失败！");
        });
    },
    handlerGetBizData(bizId) {
      //获取表单数据
      request.get("otc-mgr/taskform/" + this.query.taskId).then(res => {
        //清空历史审批记录
        this.totalData = res.data;
        this.finishedData = {
          finished: res.data.finished,
          canSubmit: res.data.canSubmit,
          canView: res.data.canView
        };
        let tag = JSON.parse(res.data.modelJson).bizData;
        //审批按钮编辑
        if (this.totalData.userChoices) {
          let checkResult = this.$refs.realize.handlerFindItem(
              "checkResult",
              this.formConfig.column
            ),
            checkResultList = [];
          const userChoices = JSON.parse(this.totalData.userChoices);
          for (let key in userChoices) {
            checkResultList.push({
              value: key,
              label: userChoices[key]
            });
          }
          this.$set(checkResult.insideData, "dataList", checkResultList);
        }

        //审批历史数据
        if (!res.data.taskRealFinished) {
          if (tag.memo) {
            delete tag.memo;
          }
          if (tag.checkResult) {
            delete tag.checkResult;
          }
        }

        this.formData = tag;
        //详情页
        if (this.query.nodeId == "detial") {
          this.$set(this.formConfig, "disable", true);
        }

        //获取历史审批
        this.handlerhistoryNode();

        this.loading = false;
      });
      // .catch(() => {
      //   if (this.query.nodeId == "detial") {
      //     this.$set(this.formConfig, "disable", true);
      //   }
      //   this.loading = false;
      //   this.$message.error("获取详情失败！");
      // });
    },
    //表单提交
    formSubmit(data) {
      this.$confirm("您确定要提交吗？", "流程提交", {
        type: "warning"
      }).then(() => {
        this.loading = true;
        if (this.query.nodeId != "apply") {
          //审批提交
          this.handlerApprove(data);
        } else {
          //申请页
          let submitData = {
            bizData: data
          };
          console.log(JSON.stringify(submitData));
          request
            .post(`otc-mgr/applyform/submitInner/${this.query.id}`, submitData)
            .then(
              res => {
                this.loading = false;
                console.log(res);
                if (res.data.success) {
                  this.$message.info("提交成功");
                  this.$router.push("/queryPage/bjotcProcessMonitor");
                } else {
                  this.$message.error(res.ErrorCode);
                }
              },
              err => {
                //提示
                this.loading = false;
                this.$message.error("提交失败");
              }
            );
        }
      });
    },

    handlerApprove(data) {
      //数据处理
      let tag = JSON.parse(JSON.stringify(data));

      if (tag.historyNode) {
        delete tag.historyNode;
      }

      this.totalData.checkResult = tag.checkResult;
      this.totalData.memo = tag.memo;
      this.totalData.formVars = {};

      let t = JSON.parse(this.totalData.modelJson);
      t.bizData = tag;

      this.totalData.modelJson = JSON.stringify(t);

      request
        .post(
          "otc-mgr/taskform/" + this.query.taskId + "/submit",
          this.totalData
        )
        .then(
          res => {
            this.loading = false;
            if (res.data["0"] == "success") {
              this.$msgUtil.successTip("提交成功！", () => {
                this.$router.push("/queryPage/bjotcProcessMonitor");
              });
            } else {
              this.$message.error(res.ErrorCode);
            }
          },
          err => {
            //提示
            this.loading = false;
            this.$message.error("提交失败");
          }
        );
    },
    handlerhistoryNode() {
      //获取历史审批信息
      request
        .get(
          "otc-mgr/taskform/" +
            this.query.bizId +
            "/taskProcess?includeRead=true&includeFuture=false&includeAutoNode=false"
        )
        .then(res => {
          let disposeNotes = res.data;
          if (disposeNotes.length) {
            this.formData.historyNode = [];
            for (let i = 0; i < disposeNotes.length; i++) {
              if (disposeNotes[i].taskItemState == 3) {
                this.formData.historyNode.push(disposeNotes[i]);
              }
            }
          }
        });
    }
  }
};
</script>


<style lang="scss">
#processForm {
  min-height: 70vh;
  .processForm {
    padding: 10px 30px;
    margin-bottom: 20px;
    background-color: #fff;
  }

  margin: 10px 0;
  background: white;
  padding: 20px;
  padding: 20px !important;
}
</style>
